
'''	
	This file is part of Roseena.
	
	Copyright (C) 2008	Mohamed Hazem <mohamed.hazem@student.guc.edu.eg>
	Copyright (C) 2008	Mostafa Hany <mostafa.hany@student.guc.edu.eg>

	
	Roseena is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	Roseena is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with Roseena.	If not, see <http://www.gnu.org/licenses/>.
'''


from PyQt4.QtCore import QDataStream, QString, QIODevice, QByteArray, QFile, SIGNAL
from PyQt4.QtGui import QWidget, QVBoxLayout, QHBoxLayout, QPlainTextEdit, QLineEdit, QPushButton, QTextEdit, QFont, QApplication
from PyQt4.QtNetwork import QTcpSocket, QHostAddress
import sys

HOST = QHostAddress(QHostAddress.LocalHost)
PORT = 8000
SIZEOF_UINT16 = 2

class ClientWindow(QWidget):
	"""
	Client's window class
	"""

	def __init__(self):
		"""
		Constructor
		"""
		app = QApplication(sys.argv)

		QWidget.__init__(self)

		self.requestString = ""
		self.fileSize = -1
		self.received = 0

		self.file = None

		self.socket = QTcpSocket()

		self.connect(self.socket, SIGNAL("connected()"), self.sendRequest)
		self.connect(self.socket, SIGNAL("readyRead()"), self.readResponse)

		self.requestEntryLine = QLineEdit()
		self.requestEntryLine.setFixedSize(300, 25)


		self.infoArea = QPlainTextEdit()
		self.infoArea.setReadOnly(True)

		font = QFont()
		font.setBold(True)

		self.infoArea.setFont(font)

		sendRequestButton = QPushButton("Send Request")
		self.connect(sendRequestButton, SIGNAL("clicked()"), self.buttonClicked)

		horizontalBox = QHBoxLayout()
		verticalBox = QVBoxLayout()

		horizontalBox.addWidget(self.requestEntryLine)
		horizontalBox.addWidget(sendRequestButton)

		verticalBox.addLayout(horizontalBox)
		verticalBox.addWidget(self.infoArea)

		self.setLayout(verticalBox)
		self.setGeometry(0, 200, 400, 400)
		self.setFixedSize(400, 400)
		self.setWindowTitle("Client")
		self.show()


		sys.exit(app.exec_())

	def buttonClicked(self):
		"""
		Method responsible for updating the UI and issuing the request
		after the clicked() signal is emitted.
		"""
		self.issueRequest(self.requestEntryLine.text())
		self.infoArea.appendPlainText("Request " + "'" + self.requestEntryLine.text() + "'" + " Sent")
		self.requestEntryLine.clear()


	def issueRequest(self, requestString):
		"""
		Method responsible for issuing requests.

		Example: issueRequest("GET index.html HTTP/1.0")
		"""
		self.requestString = str(requestString)

		if self.socket.isOpen():
			self.socket.close()

		self.fileSize = -1
		self.received = 0
		if self.file != None:
			self.file.close()

		self.socket.connectToHost(HOST, PORT)

	def sendRequest(self):
		"""
		Method responsible for sending the request after the
		connected() signal is emitted.
		"""
		self.socket.write(self.requestString + "\n")
#		self.file = QFile("files/" + self.requestString.split(" ")[1])

	def readResponse(self):
		"""
		Method responsible for reading the server's response and updating the UI.
		"""

		if self.fileSize == -1:
			print "file size -1"
			if self.socket.canReadLine() == False:
				print "file can readline false return"
				return
			response = self.socket.readLine()
			print "Response is: " + str(response)
			self.infoArea.appendPlainText("Got Reply: " + str(response))
			if response.startsWith("Content-Length:"):
				self.fileSize = int(response.split(" ")[1])
				self.file = QFile("files/" + self.requestString.split(" ")[1])
				self.file.open(QIODevice.WriteOnly)
			return

		data = self.socket.readAll()
		self.received = self.received + len(data)
		self.file.write(data)
		if self.fileSize == self.received:
			self.file.close()
			self.infoArea.appendPlainText("Transfer of '" + self.file.fileName() + "' completed.\n")
			self.file = None

#		if self.fileSize != -1:
#			self.saveAndSend()
#		else:
#			while self.serverSocket.canReadLine() == True:
#				if self.fileSize == -1:
#					resp = self.serverSocket.readLine()
#					self.processLine(resp)
#				else:
#					return self.doServerRead()